﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace UploadBlobToAzure
{
    public partial class downloadBlob : Form
    {
        field_validator fv = new field_validator();
        public List<string> blobList = new List<string>();
        string folderLocation=string.Empty;
        string folderName=string.Empty;
        string blobEndPoint=string.Empty;
        string accountKey=string.Empty;
        string folderToBeDownloaded=string.Empty;
        string fileToBeDownloaded=string.Empty;
        string[] linesDestLog={string.Empty};
        string totalFilesTransfered = string.Empty;
        string filesTranferedSuccessfully = string.Empty;
        string filesFailed = string.Empty; 
        public downloadBlob()
        {
            InitializeComponent();
            lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
        }

        public void setBlobList(List<string> m_blobList)
        {
            blobList.AddRange(m_blobList);
            cmbLocation.DataSource = blobList;
        }

        public void setBlobEndPoint(string m_blobEndPoint)
        {
            blobEndPoint = m_blobEndPoint;
        }

        public void setaccountKey(string m_accountKey)
        {
            accountKey = m_accountKey;
        }



        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (browseFolder.ShowDialog() == DialogResult.OK)
            {
                folderLocation = browseFolder.SelectedPath.Trim();
                folderName = Path.GetFileName(folderLocation);
            }
            else
            {
                folderName = string.Empty;
                folderLocation = string.Empty;
            }
            if (folderLocation != string.Empty)
            {
                lblFolderLocation.Text = "The Folder Selected is :" + folderLocation;
                
            }
            else
            {
                lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            cmbLocation.SelectedItem = string.Empty;
            folderName = string.Empty;
            folderLocation = string.Empty;
            lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
        }



        private void cmbLocation_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) { return; }
            string text = cmbLocation.GetItemText(cmbLocation.Items[e.Index]);
            e.DrawBackground();
            using (SolidBrush br = new SolidBrush(e.ForeColor))
            { e.Graphics.DrawString(text, e.Font, br, e.Bounds); }
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            { toolTip1.Show(text, cmbLocation, e.Bounds.Right, e.Bounds.Bottom); }
            e.DrawFocusRectangle();
        }

        private void cmbLocation_DropDownClosed(object sender, EventArgs e)
        {
            toolTip1.Hide(cmbLocation);
        }

        private void cmbLocation_Leave(object sender, EventArgs e)
        {
            toolTip1.Hide(cmbLocation);
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            fileToBeDownloaded = cmbLocation.SelectedItem.ToString().Substring((cmbLocation.SelectedItem.ToString().LastIndexOf("/")) + 1);
            folderToBeDownloaded = cmbLocation.SelectedItem.ToString().Substring(0, cmbLocation.SelectedItem.ToString().LastIndexOf("/"));
            string extension=fileToBeDownloaded.Substring(fileToBeDownloaded.IndexOf(".")+1);
            
            try
            {
                if (fv.testIfFieldEmpty(cmbLocation.SelectedItem.ToString()))
                {
                    MessageBox.Show("Please select a Azure Blob To Download");
                    this.DialogResult = DialogResult.None;
                }
                else if(fv.testIfFieldEmpty(folderLocation))
                {
                    MessageBox.Show("Please select a Local Location To Download The Blob!!");
                    this.DialogResult = DialogResult.None;
                }
                else if(extension.Equals("vhd"))
                {
                    MessageBox.Show("Cannot download the vhd of the VM from Azure!!,Please choose files of some other extension");
                    this.DialogResult = DialogResult.None;
                }
                else if (fileToBeDownloaded.IndexOf(".")!=-1)
                {
                    Process cmd = new Process();
                    ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                    azcopyProcessStartInfo.FileName = "CMD.exe";
                    string cmdToBeExecuted = " azcopy.exe" + "  \"" + blobEndPoint + folderToBeDownloaded.Substring(1) + "\"  " + "  \"" + folderLocation + "\"  " + fileToBeDownloaded + "  /sourceKey:" + accountKey + "  /S   /v  /Y  >dest.log";
                    azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                    azcopyProcessStartInfo.UseShellExecute = false;
                    azcopyProcessStartInfo.CreateNoWindow = true;
                    azcopyProcessStartInfo.RedirectStandardError = true;
                    cmd.StartInfo = azcopyProcessStartInfo;
                    cmd.Start();
                    if (!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                    {
                        MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                    }
                    cmd.WaitForExit();

                    /*validate the activity*/
                    int output = validateCompletedRequest();
                    if (output == 0)
                    {
                        this.DialogResult = DialogResult.None;
                    }
                    else if (output == 1)
                    {
                        this.Close();
                    }
                    else if (output == 2)
                    {
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();
                    }         
                }
                else
                {
                    Process cmd = new Process();
                    ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                    azcopyProcessStartInfo.FileName = "CMD.exe";
                    string cmdToBeExecuted = " azcopy.exe" + "  \"" + blobEndPoint + cmbLocation.SelectedItem.ToString().Substring(1)  + "\"  " + "  \"" + folderLocation + "\"  " + " /sourceKey:" + accountKey + "  /S   /v  /Y  >dest.log";
                   azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                    azcopyProcessStartInfo.UseShellExecute = false;
                    azcopyProcessStartInfo.CreateNoWindow = true;
                    azcopyProcessStartInfo.RedirectStandardError = true;
                    cmd.StartInfo = azcopyProcessStartInfo;
                    cmd.Start();
                    //if (!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                    //{
                    //    MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                    //}
                    cmd.WaitForExit();

                    /*validate the activity*/
                    int output = validateCompletedRequest();
                    if (output == 0)
                    {
                        this.DialogResult = DialogResult.None;
                    }
                    else if (output == 1)
                    {
                        this.Close();
                    }
                    else if (output == 2)
                    {
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();
                    }         
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.DialogResult = DialogResult.None;
            }

            

                   
        }


        private int validateCompletedRequest()
        {
            if (!File.Exists("dest.log"))
            {
                MessageBox.Show("The status of the Last operation cannot be determined as the Log file failed to generate in the application directory");
                //this.DialogResult = DialogResult.None;
                return 0;
            }
            else
            {
                linesDestLog = File.ReadAllLines("dest.log");
                foreach (var line in linesDestLog)
                {
                    if (line.Contains("Total files transferred"))
                    {
                        totalFilesTransfered = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                    else if (line.Contains("Transfer successfully"))
                    {
                        filesTranferedSuccessfully = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                    else if (line.Contains("Transfer failed"))
                    {
                        filesFailed = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                }

                if (totalFilesTransfered == null || filesTranferedSuccessfully == null)
                {
                    MessageBox.Show("The status of the Last operation cannot be determined as the Log file failed to generate in the application directory");
                    //this.DialogResult = DialogResult.None;
                    return 0;
                }

                if (totalFilesTransfered.Equals(filesTranferedSuccessfully))
                {
                    DialogResult result = MessageBox.Show("All Files Transfered Successfully!!, You want to transfer another set of files?", "Question", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //this.DialogResult = DialogResult.None;
                        return 0;
                    }
                    else
                    {
                        //this.Close();
                        return 1;
                    }
                }
                else if (filesTranferedSuccessfully == "0")
                {
                    MessageBox.Show("The Operation Failed, Kindly refer to the Dest.log in the Application directory for more details");

                    //this.DialogResult = DialogResult.Cancel;
                    //this.Close();
                    return 2;
                }
                else
                {
                    MessageBox.Show("Sone of the Files did not upload successfully, Please refer to the dest.log in the Application directory for details");
                    //this.Close();
                    return 1;
                }
            }
        }
     }
}
